package com.nbsaas.boot.service.impl;

import com.nbsaas.boot.entity.Question;
import com.nbsaas.boot.repository.QuestionRepository;
import com.nbsaas.boot.service.QuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class QuestionServiceImpl implements QuestionService {
    
    private final QuestionRepository questionRepository;

    @Override
    @Transactional
    public Question createQuestion(Question question) {
        return questionRepository.save(question);
    }

    @Override
    @Transactional
    public Question updateQuestion(Long id, Question question) {
        Question existingQuestion = questionRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("题目不存在"));
        
        existingQuestion.setTitle(question.getTitle());
        existingQuestion.setDescription(question.getDescription());
        existingQuestion.setInitialCode(question.getInitialCode());
        existingQuestion.setTestCases(question.getTestCases());
        existingQuestion.setDifficulty(question.getDifficulty());
        existingQuestion.setCategory(question.getCategory());
        existingQuestion.setTimeLimit(question.getTimeLimit());
        existingQuestion.setMemoryLimit(question.getMemoryLimit());
        
        return questionRepository.save(existingQuestion);
    }

    @Override
    @Transactional
    public void deleteQuestion(Long id) {
        questionRepository.deleteById(id);
    }

    @Override
    public Question getQuestion(Long id) {
        return questionRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("题目不存在"));
    }

    @Override
    public Page<Question> searchQuestions(String category, String difficulty, String keyword, Pageable pageable) {
        return questionRepository.search(category, difficulty, keyword, pageable);
    }
} 